package uk.co.javahelp.sender.cli;

import static org.apache.commons.lang3.StringUtils.substringAfterLast;

import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;

import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;

import uk.co.javahelp.sender.bulk.BulkSender;
import uk.co.javahelp.sender.message.Attachment;

public class Main {

	public static void main(final String[] args) throws IOException, InterruptedException {
		final Reader reader;
		final String template = "default";
		final long throttle = 2000L;
		final Attachment[] attachments;
		
		if(args == null || args.length == 0) {
			System.out.println("*** THIS IS A TEST RUN ***");
		    reader = new InputStreamReader(Main.class.getResourceAsStream("/test.csv"));
	    	//attachments = new Attachment[]{new Attachment("picture.jpg", new ClassPathResource("/picture-large.jpg"))};
		    	attachments = new Attachment[0];
		} else {
		    reader = new FileReader(args[0]);
	    	attachments = new Attachment[0];
		    /*
		    if(args.length > 1) {
		    	attachments = new Attachment[]{new Attachment(substringAfterLast(args[1], "/"), new FileSystemResource(args[1]))};
		    } else {
		    	attachments = new Attachment[0];
		    }
		    */
		}
		
        PropertySourcesPlaceholderConfigurer pph = new PropertySourcesPlaceholderConfigurer();
        pph.setLocation(new FileSystemResource(args[1]));
        
		final ClassPathXmlApplicationContext cxt = new ClassPathXmlApplicationContext();
		cxt.registerShutdownHook();
		cxt.setConfigLocation("classpath*:META-INF/spring/*.xml");
        cxt.addBeanFactoryPostProcessor(pph);
		cxt.refresh();
		cxt.start();
		
		final BulkSender bulkSender = cxt.getBean(BulkSender.class);
		bulkSender.sendInBulk(template, reader, throttle, attachments);
		
		cxt.stop();
	}
}
